package com.forum.model.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.forum.model.pojo.ForumUser;
import com.forum.model.util.SessionManager;

public class ForumUserDAO implements GenericDAO<ForumUser, Long> {

	private Session session;

	@Override
	public boolean insert(ForumUser forumUser) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(forumUser);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean update(ForumUser forumUser) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(forumUser);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean delete(ForumUser forumUser) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(forumUser);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public ForumUser getObjectById(Long id) {
		ForumUser user = null;
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			user = (ForumUser) session.get(ForumUser.class, id);
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return user;
	}
	
	public ForumUser getUserByLoginName(String loginName){
		ForumUser user = null;
		Query query;
		try{
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			query = session.createQuery("from ForumUser where loginName= ?");
			query.setString(0, loginName);
			user = (ForumUser)query.list().get(0);
			session.getTransaction().commit();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}finally{
			SessionManager.closeSession(session);
		}
		return user;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<ForumUser> getAll() {
		List<ForumUser> all = null;

		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<ForumUser>) session.createQuery("from ForumUser")
					.list();
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}

		return all;
	}
}